<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;
use App\Models\OrderGoods;

/**
 * @property mixed pay_type 支付方式 1支付宝， 2微信，3余额
 * @property mixed user
 */
class Order extends Model
{

    protected $table = 'order_info';
    public $timestamps = false;
    protected $fillable = ['order_no', 'store_id', 'user_id', 'user_name', 'consignee',
        'phone', 'province', 'district', 'city', 'address', 'addresses', 'leave_msg', 'order_status', 'return_status',
        'is_lock', 'goods_amount', 'order_amount', 'logistics_amount','discount_amount','commission_amount','reward_wheat', 'remark', 'pay_type', 'source',
        'is_show', 'pay_at', 'delivery_at', 'finish_at', 'cancel_at', 'delete_at', 'created_at', 'updated_at'];

    public function goods()
    {
        return $this->hasMany('App\Models\OrderGoods', 'order_id', 'id');
    }

    public function store(){
        return $this->belongsTo('App\Models\Store','store_id','id');
    }

    public function toESArray()
    {
        // 只取出需要的字段
        $arr = Arr::only($this->toArray(), [
            'id',
            'order_no',
            'user_name',
            'consignee',
            'addresses',
            'order_status',
            'order_amount',
            'created_at',
        ]);
        $arr['store_name'] = $this->store->store_name;
        // 只取出需要的 goods 字段
        $arr['goods'] = $this->goods->map(function (OrderGoods $goods){
            return Arr::only($goods->toArray(),['goods_name', 'goods_spec', 'goods_price']);
        });
        //随机生成属性
        $arr['properties'] = collect($this->getProperties())->map(function($properties,$key){
            return array_merge($properties, [
                'search_value' => $properties['name'].':'.$properties['value'],
            ]);
        });
        return $arr;
    }

    public function getProperties(){
        $params = [];
        $params1 = [
            ["name" => "品牌名称", "value" => "金士顿"],
            ["name" => "品牌名称", "value" => "海盗船"],
            ["name" => "品牌名称", "value" => "三星"],
            ["name" => "品牌名称", "value" => "影驰"],
            ["name" => "品牌名称", "value" => "威刚"],
        ];
        $params2 = [
            ["name" => "内存容量", "value" => "8GB"],
            ["name" => "内存容量", "value" => "4GB"],
            ["name" => "内存容量", "value" => "16GB"],
        ];
        $params3 = [
            ["name" => "传输类型", "value" => "DDR4"],
            ["name" => "传输类型", "value" => "DDR3"],
        ];
        $params[] = $params1[rand(0,4)];
        $randNum = rand(1,3);
        foreach($params2 as $k=> $val){
            if($k<$randNum){
                $params[] = $val;
            }else{
                break;
            }
        }
        $params[] = $params3[rand(0,1)];
        return $params;
    }

}
